from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core.paginator import Paginator
from django.db import transaction
from django.utils import timezone
import json
import logging

from .models import CloudAccount, Domain, DNSRecord, OperationLog, CloudProvider, RecordType
from .cloud_providers import get_dns_provider
from .forms import CloudAccountForm, DomainForm, DNSRecordForm

logger = logging.getLogger(__name__)


def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def home(request):
    """首页"""
    if not request.user.is_authenticated:
        return render(request, 'dns_manager/home.html')
    
    # 统计数据
    cloud_accounts_count = CloudAccount.objects.filter(user=request.user, is_active=True).count()
    domains_count = Domain.objects.filter(user=request.user, is_active=True).count()
    records_count = DNSRecord.objects.filter(user=request.user, is_active=True).count()
    
    # 最近操作日志
    recent_logs = OperationLog.objects.filter(user=request.user)[:5]
    
    context = {
        'cloud_accounts_count': cloud_accounts_count,
        'domains_count': domains_count,
        'records_count': records_count,
        'recent_logs': recent_logs,
    }
    return render(request, 'dns_manager/dashboard.html', context)


@login_required
def cloud_accounts(request):
    """云账号管理"""
    accounts = CloudAccount.objects.filter(user=request.user).order_by('-created_at')
    return render(request, 'dns_manager/cloud_accounts.html', {'accounts': accounts})


@login_required
def create_cloud_account(request):
    """创建云账号"""
    if request.method == 'POST':
        form = CloudAccountForm(request.POST)
        if form.is_valid():
            account = form.save(commit=False)
            account.user = request.user
            account.save()
            
            # 记录操作日志
            OperationLog.objects.create(
                user=request.user,
                action='create',
                resource_type='CloudAccount',
                resource_id=str(account.id),
                description=f'创建云账号: {account.name}',
                ip_address=get_client_ip(request)
            )
            
            # 自动同步域名和DNS记录
            try:
                from .cloud_providers import sync_cloud_account_domains
                sync_stats = sync_cloud_account_domains(account)
                
                success_msg = f'云账号 "{account.name}" 创建成功'
                if sync_stats['domains_added'] > 0 or sync_stats['records_added'] > 0:
                    success_msg += f'，已同步 {sync_stats["domains_added"]} 个域名和 {sync_stats["records_added"]} 个DNS记录'
                    
                    # 记录同步日志
                    OperationLog.objects.create(
                        user=request.user,
                        action='sync',
                        resource_type='CloudAccount',
                        resource_id=str(account.id),
                        description=f'自动同步云账号 {account.name}: 域名{sync_stats["domains_added"]}个，DNS记录{sync_stats["records_added"]}个',
                        ip_address=get_client_ip(request)
                    )
                    
                messages.success(request, success_msg)
                
                # 如果有错误，显示警告
                if sync_stats['errors']:
                    for error in sync_stats['errors'][:3]:  # 只显示前3个错误
                        messages.warning(request, f'同步警告: {error}')
                        
            except Exception as e:
                messages.warning(request, f'云账号创建成功，但自动同步失败: {e}')
            
            return redirect('cloud_accounts')
    else:
        form = CloudAccountForm()
    
    return render(request, 'dns_manager/create_cloud_account.html', {'form': form})


@login_required
def edit_cloud_account(request, account_id):
    """编辑云账号"""
    account = get_object_or_404(CloudAccount, id=account_id, user=request.user)
    
    if request.method == 'POST':
        form = CloudAccountForm(request.POST, instance=account)
        if form.is_valid():
            account = form.save()
            
            # 记录操作日志
            OperationLog.objects.create(
                user=request.user,
                action='update',
                resource_type='CloudAccount',
                resource_id=str(account.id),
                description=f'更新云账号: {account.name}',
                ip_address=get_client_ip(request)
            )
            
            messages.success(request, f'云账号 "{account.name}" 更新成功')
            return redirect('cloud_accounts')
    else:
        # 清空密钥字段以保护隐私
        form = CloudAccountForm(instance=account)
        form.fields['secret_key'].initial = ''
    
    return render(request, 'dns_manager/edit_cloud_account.html', {'form': form, 'account': account})


@login_required
def delete_cloud_account(request, account_id):
    """删除云账号"""
    account = get_object_or_404(CloudAccount, id=account_id, user=request.user)
    
    if request.method == 'POST':
        account_name = account.name
        account.delete()
        
        # 记录操作日志
        OperationLog.objects.create(
            user=request.user,
            action='delete',
            resource_type='CloudAccount',
            resource_id=str(account_id),
            description=f'删除云账号: {account_name}',
            ip_address=get_client_ip(request)
        )
        
        messages.success(request, f'云账号 "{account_name}" 删除成功')
        return redirect('cloud_accounts')
    
    return render(request, 'dns_manager/confirm_delete.html', {
        'object': account,
        'object_type': '云账号',
        'cancel_url': 'cloud_accounts'
    })


@login_required
def sync_cloud_account(request, account_id):
    """手动同步云账号域名和DNS记录"""
    account = get_object_or_404(CloudAccount, id=account_id, user=request.user)
    
    try:
        from .cloud_providers import sync_cloud_account_domains
        sync_stats = sync_cloud_account_domains(account)
        
        # 记录操作日志
        OperationLog.objects.create(
            user=request.user,
            action='sync',
            resource_type='CloudAccount',
            resource_id=str(account.id),
            description=f'手动同步云账号 {account.name}: 新增域名{sync_stats["domains_added"]}个，更新域名{sync_stats["domains_updated"]}个，新增DNS记录{sync_stats["records_added"]}个，更新DNS记录{sync_stats["records_updated"]}个',
            ip_address=get_client_ip(request)
        )
        
        # 构建成功消息
        success_parts = []
        if sync_stats['domains_added'] > 0:
            success_parts.append(f'新增域名 {sync_stats["domains_added"]} 个')
        if sync_stats['domains_updated'] > 0:
            success_parts.append(f'更新域名 {sync_stats["domains_updated"]} 个')
        if sync_stats['records_added'] > 0:
            success_parts.append(f'新增DNS记录 {sync_stats["records_added"]} 个')
        if sync_stats['records_updated'] > 0:
            success_parts.append(f'更新DNS记录 {sync_stats["records_updated"]} 个')
            
        if success_parts:
            success_msg = f'同步完成：' + '、'.join(success_parts)
        else:
            success_msg = '同步完成，没有新的域名或DNS记录'
            
        messages.success(request, success_msg)
        
        # 如果有错误，显示警告
        if sync_stats['errors']:
            for error in sync_stats['errors'][:5]:  # 只显示前5个错误
                messages.warning(request, f'同步警告: {error}')
                
    except Exception as e:
        messages.error(request, f'同步失败: {e}')
        
    return redirect('cloud_accounts')


@login_required
def domains(request):
    """域名管理"""
    domains_list = Domain.objects.filter(user=request.user).select_related('cloud_account').order_by('-created_at')
    
    paginator = Paginator(domains_list, 20)
    page_number = request.GET.get('page')
    domains = paginator.get_page(page_number)
    
    return render(request, 'dns_manager/domains.html', {'domains': domains})


@login_required
def create_domain(request):
    """添加域名"""
    if request.method == 'POST':
        form = DomainForm(request.POST, user=request.user)
        if form.is_valid():
            domain = form.save(commit=False)
            domain.user = request.user
            domain.save()
            
            # 记录操作日志
            OperationLog.objects.create(
                user=request.user,
                action='create',
                resource_type='Domain',
                resource_id=str(domain.id),
                description=f'添加域名: {domain.name}',
                ip_address=get_client_ip(request)
            )
            
            messages.success(request, f'域名 "{domain.name}" 添加成功')
            return redirect('domains')
    else:
        form = DomainForm(user=request.user)
    
    return render(request, 'dns_manager/create_domain.html', {'form': form})


@login_required
def domain_records(request, domain_id):
    """域名解析记录"""
    domain = get_object_or_404(Domain, id=domain_id, user=request.user)
    records_list = DNSRecord.objects.filter(domain=domain, user=request.user).order_by('name', 'record_type')
    
    paginator = Paginator(records_list, 50)
    page_number = request.GET.get('page')
    records = paginator.get_page(page_number)
    
    return render(request, 'dns_manager/domain_records.html', {
        'domain': domain,
        'records': records
    })


@login_required
def create_dns_record(request, domain_id):
    """创建DNS记录"""
    domain = get_object_or_404(Domain, id=domain_id, user=request.user)
    
    if request.method == 'POST':
        form = DNSRecordForm(request.POST)
        if form.is_valid():
            record = form.save(commit=False)
            record.domain = domain
            record.user = request.user
            
            try:
                # 调用云服务API创建记录
                provider = get_dns_provider(
                    domain.cloud_account.provider,
                    domain.cloud_account.access_key,
                    domain.cloud_account.get_decrypted_secret_key(),
                    domain.cloud_account.region
                )
                
                result = provider.create_record(
                    domain.name,
                    record.name,
                    record.record_type,
                    record.value,
                    record.ttl,
                    record.priority,
                    domain.zone_id
                )
                
                if result.get('success'):
                    record.record_id = result.get('record_id', '')
                    record.save()
                    
                    # 记录操作日志
                    OperationLog.objects.create(
                        user=request.user,
                        action='create',
                        resource_type='DNSRecord',
                        resource_id=str(record.id),
                        description=f'创建DNS记录: {record.name}.{domain.name}',
                        ip_address=get_client_ip(request)
                    )
                    
                    messages.success(request, f'DNS记录 "{record.name}.{domain.name}" 创建成功')
                    return redirect('domain_records', domain_id=domain.id)
                else:
                    messages.error(request, f'创建DNS记录失败: {result.get("message", "未知错误")}')
                    
            except Exception as e:
                logger.error(f"创建DNS记录失败: {e}")
                messages.error(request, f'创建DNS记录失败: {str(e)}')
    else:
        form = DNSRecordForm()
    
    return render(request, 'dns_manager/create_dns_record.html', {
        'form': form,
        'domain': domain
    })


@login_required
def sync_domain_records(request, domain_id):
    """从云端同步域名解析记录"""
    domain = get_object_or_404(Domain, id=domain_id, user=request.user)
    
    try:
        provider = get_dns_provider(
            domain.cloud_account.provider,
            domain.cloud_account.access_key,
            domain.cloud_account.get_decrypted_secret_key(),
            domain.cloud_account.region
        )
        
        # 获取云端记录
        cloud_records = provider.list_records(domain.name, domain.zone_id)
        
        with transaction.atomic():
            # 清除现有记录（可选，这里选择不清除，而是标记为非活跃）
            # DNSRecord.objects.filter(domain=domain).delete()
            
            synced_count = 0
            for cloud_record in cloud_records:
                record, created = DNSRecord.objects.get_or_create(
                    domain=domain,
                    name=cloud_record['name'],
                    record_type=cloud_record['type'],
                    value=cloud_record['value'],
                    user=request.user,
                    defaults={
                        'ttl': cloud_record.get('ttl', 600),
                        'priority': cloud_record.get('priority', 0),
                        'record_id': cloud_record.get('record_id', ''),
                        'is_active': True
                    }
                )
                
                if not created:
                    # 更新现有记录
                    record.ttl = cloud_record.get('ttl', 600)
                    record.priority = cloud_record.get('priority', 0)
                    record.record_id = cloud_record.get('record_id', '')
                    record.is_active = True
                    record.save()
                
                synced_count += 1
            
            # 更新域名的最后同步时间
            domain.last_sync = timezone.now()
            domain.save()
        
        # 记录操作日志
        OperationLog.objects.create(
            user=request.user,
            action='sync',
            resource_type='Domain',
            resource_id=str(domain.id),
            description=f'同步域名记录: {domain.name}，同步了 {synced_count} 条记录',
            ip_address=get_client_ip(request)
        )
        
        messages.success(request, f'成功同步了 {synced_count} 条DNS记录')
        
    except Exception as e:
        logger.error(f"同步域名记录失败: {e}")
        messages.error(request, f'同步失败: {str(e)}')
    
    return redirect('domain_records', domain_id=domain.id)


@login_required
def operation_logs(request):
    """操作日志"""
    logs_list = OperationLog.objects.filter(user=request.user).order_by('-created_at')
    
    paginator = Paginator(logs_list, 50)
    page_number = request.GET.get('page')
    logs = paginator.get_page(page_number)
    
    return render(request, 'dns_manager/operation_logs.html', {'logs': logs})


def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip
